package cn.sc.summer.warm.listener;

import cn.sc.summer.warm.handler.WarmupHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 类名：服务器启动监听器
 *
 * @author a-xin
 * @date 16:38
 */
@Slf4j
@Component
public class WarmupListener implements ApplicationListener<ApplicationReadyEvent> {

    @Resource
    private WarmupHandler handler;

    @Value("${project.warmup.enabled:true}")
    private Boolean ENABLED;

    @Override
    public void onApplicationEvent(@NonNull ApplicationReadyEvent event) {
        if (Boolean.FALSE.equals(ENABLED)) {
            return;
        }
        ConfigurableApplicationContext applicationContext = event.getApplicationContext();
        if (applicationContext instanceof ServletWebServerApplicationContext) {
            handler.warmupLocalhost(applicationContext);
            log.info("-> The interface is warmed up!");
        }
    }

}
